package tech.wetech.admin.service.system.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tech.wetech.admin.common.base.Page;
import tech.wetech.admin.common.base.PageResultSet;
import tech.wetech.admin.mapper.system.BillMapper;
import tech.wetech.admin.model.system.Bill;
import tech.wetech.admin.model.system.BillExample;
import tech.wetech.admin.model.system.BizException;
import tech.wetech.admin.service.system.BillService;
import tech.wetech.admin.web.dto.system.BillData;

import java.util.ArrayList;
import java.util.List;

@Service
public class BillServiceImpl implements BillService {

    @Autowired
    private BillMapper billMapper;
    @Override
    public int createBill(Bill bill) throws BizException {

        return billMapper.insert(bill);
    }

    @Override
    public int updateBill(Bill bill) {
        return billMapper.updateByPrimaryKeySelective(bill);
    }

    @Override
    public void deleteBill(Long billId) {
        billMapper.deleteByPrimaryKey(billId);
    }

    @Override
    public PageResultSet<Bill> findByPage(Page page) {

        BillExample example = new BillExample();

        // 设置分页参数
        example.setOffset(page.getOffset());
        example.setLimit(page.getLimit());

        // 设置搜索条件
        if (!StringUtils.isEmpty(page.getSearch())) {
            example.or().andNameLike("%" + page.getSearch() + "%");
        }

        // 设置排序条件
        if (!StringUtils.isEmpty(page.getSort()) && page.getOrder() != null) {
            String orderByClause = page.getSort() + " " + page.getOrder().name();
            example.setOrderByClause(orderByClause);
        }

        // 查询总数
        long count = billMapper.countByExample(example);

        // 构建返回结果
        List<Bill> dtoList = new ArrayList<>();
        PageResultSet<Bill> resultSet = new PageResultSet<>();
        billMapper.selectByExample(example).forEach(u -> {
            /*dto.setOrganizationName(getOrganizationName(Long.valueOf(dto.getOrganizationId())));
            dto.setRoleNames(getRoleNames(dto.getRoleIdList()));*/
            dtoList.add(u);
        });
        resultSet.setRows(dtoList);
        resultSet.setTotal(count);
        return resultSet;
    }

    @Override
    public List<Bill> findByExample(BillExample example) {
        List<Bill> billList = new ArrayList<>();
        billList = billMapper.selectByExample(example);
        return billList;
    }

    @Override
    public List<BillData> findExpenseInfo( String year) {
        List<BillData> billdata = new ArrayList<BillData>();
        billdata = billMapper.selectExpenseInfo(year);
        return billdata;
    }

    @Override
    public  List<BillData> findIncomeInfo(String year) {
        List<BillData> billdata = new ArrayList<BillData>();
        billdata = billMapper.selectIncomeInfo(year);
        return billdata;
    }

}
